<?php

//
//  Created by Chagan Anton on 29.07.12.
//  Copyright Chagan Anton 2012. All rights reserved.
//
class TpLocationController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('view', 'tpinfo', 'email'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'ajaxcreate', 'index'),
                'roles' => array('admin', 'root'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('admin', 'delete', 'updateTest'),
                'roles' => array('admin', 'root'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionTpInfoView($id) {
        $this->render('tpView', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new TPLocation;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['TPLocation'])) {
            $model->attributes = $_POST['TPLocation'];
            $model->dateSubscription = date("Y-m-d", time() + 60 * 60 * 24 * 30); //one month
            if ($model->save()) {
                $model->tp_uid = base_convert($model->id, 10, 36);
                $model->save();
                $this->ParseJsonFile();
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionAjaxCreate() {
        $model = new TPLocation;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['TPLocation'])) {
            $model->attributes = $_POST['TPLocation'];
            $model->location = $_POST['TPLocation']['location'];
            $model->telephone_land = $_POST['TPLocation']['telephone_land'];
            $model->email = $_POST['TPLocation']['email'];
            $model->dateSubscription = date("Y-m-d", time() + 60 * 60 * 24 * 30); //one month
//            var_dump($model->attributes);
//            var_dump($_POST['TPLocation']);
            if ($model->save()) {
                $model->tp_uid = base_convert($model->id, 10, 36);
                $model->save();
                $this->sendEmail($model->id,$model->email);
                echo "1";
            }
            else
                echo "0";
        }
    }

    private function sendEmail($id, $emailAdress) {
        $model = $this->loadModel($id);
        $model->secure_url = md5((time() + time()) / 2);
        $model->expiry_link = 0;
        $model->save();

//        $location = json_decode($model->location);
        $link = $this->createAbsoluteUrl('tpLocation/tpinfo') . "&id=" . $model->secure_url;

        $mail = new YiiMailer('contact', array('link' => $link));
        $mail->setFrom('apps@appcamel.com');
        $mail->setTo($emailAdress);
        $mail->setSubject('Welcome in Dermapen app');
        if ($mail->send()) {
//            echo 'sended right';
//                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
        } else {
            echo 'emai not sended!!';
//                Yii::app()->user->setFlash('error', 'Error while sending email: ' . $mail->getError());
        }
    }

    private function ParseJsonFile() {

        $model = TPLocation::model()->findAll();
        $output = array();
        foreach ($model as $tp) {
            $loc = json_decode($tp->location);
            if ($loc == 0)
                continue;
            $temp = array
                (
                "id" => $tp->id,
                "text" => $tp->name,
                "snippet" => substr($tp->address, 0, 40),
                "telephone" => $tp->telephone_land,
                "mobile" => $tp->telephone_mob1,
                "email" => $tp->email,
                "page" => $tp->telephone_mob2,
                "date" => $tp->dateSubscription,
                "value" => array
                    (
                    "latitude" => $loc->latitude,
                    "longitude" => $loc->longitude
                ),
            );
            $output[] = $temp;
        }
        file_put_contents("DermaPenLocations.json", json_encode($output));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);
        Yii::app()->clientScript->registerPackage('jquery');
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['TPLocation'])) {
            $model->attributes = $_POST['TPLocation'];
            if ($model->save()) {
                $this->ParseJsonFile();
                $this->redirect(array('view', 'id' => $model->id));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionUpdateTest($id) {
        $this->layout = '//layouts/tpinfo';
        $model = $this->loadModel($id);
        Yii::app()->clientScript->registerPackage('jquery');
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['TPLocation'])) {
            $model->attributes = $_POST['TPLocation'];
            if ($model->save()) {
                $this->ParseJsonFile();
                $this->redirect("http://appcamel.com");
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actiontpinfo($id) {
        Yii::app()->clientScript->registerPackage('jquery');
        $this->layout = '//layouts/tpinfo';
        $model = TPLocation::model()->find('secure_url=:secure_url', array(':secure_url' => $id));
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        // when saving entered info
        if (isset($_POST['TPLocation'])) {
            $model->attributes = $_POST['TPLocation'];
            if ($model->save()) {
                $this->ParseJsonFile();
                $this->redirect("http://appcamel.com"); //array('view', 'id' => $model->id));
            }
        }
        if ($model->expiry_link == 0) {
            $model->expiry_link = time() + 60 * 60;
            $model->save();
        }
        if ($model->expiry_link < time())
            throw new CHttpException(404, 'Your link was expired.');
        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Displays the contact page
     */
    public function actionEmail() {
        echo 'email!!';
        if (isset($_POST['id'])) {

//            include('Mail.php');
//            include('Mail/mime.php');
            echo $_POST['email'];
            $model = $this->loadModel($_POST['id']);
            $model->secure_url = md5((time() + time()) / 2);
            $model->expiry_link = 0;
            $model->save();

            $location = json_decode($model->location);
            $link = $this->createAbsoluteUrl('tpLocation/tpinfo') . "&id=" . $model->secure_url;



            $mail = new YiiMailer('contact', array('link' => $link));
            $mail->setFrom('apps@appcamel.com');
            $mail->setTo($_POST['email']);
            $mail->setSubject('Welcome in Dermapen app');
            if ($mail->send()) {
                echo 'sended right';
//                Yii::app()->user->setFlash('contact', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                echo 'error!!';
//                Yii::app()->user->setFlash('error', 'Error while sending email: ' . $mail->getError());
            }
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('TPLocation');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new TPLocation('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['TPLocation']))
            $model->attributes = $_GET['TPLocation'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = TPLocation::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'tplocation-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
